package com.sicilin.common.exceptionresolver;

import com.sicilin.common.ajax.vo.AjaxResponse;
import com.sicilin.common.exception.BusinessException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by sicilin on 2017/8/1.
 */
public class ExceptionResolver implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        // 判断是否ajax请求
        if (!(httpServletRequest.getHeader("accept").indexOf("application/json") > -1 || (httpServletRequest
                .getHeader("X-Requested-With") != null && httpServletRequest.getHeader(
                "X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
            if(e instanceof Exception){
                return new ModelAndView("error");
            }
        }else {
            //当为Ajax请求时候，统一转成JSON返回
            try {
                if (e instanceof BusinessException) {
                    AjaxResponse vo = new AjaxResponse(e);
                    httpServletResponse.getWriter().print(vo.generateJSONString());
                    httpServletResponse.getWriter().flush();
                    httpServletResponse.getWriter().close();
                }else if(e instanceof UnauthorizedException){
                    Exception newe = new Exception("没有权限！");
                    AjaxResponse vo = new AjaxResponse(newe);
                    httpServletResponse.getWriter().print(vo.generateJSONString());
                    httpServletResponse.getWriter().flush();
                    httpServletResponse.getWriter().close();
                }
                else if(e instanceof AuthenticationException ){
                    Exception newe = new Exception("认证失败！");
                    AjaxResponse vo = new AjaxResponse(newe);
                    httpServletResponse.getWriter().print(vo.generateJSONString());
                    httpServletResponse.getWriter().flush();
                    httpServletResponse.getWriter().close();
                } else if (e instanceof Exception) {
                    Exception newe = new Exception("系统出错，请让管理员查看！");
                    AjaxResponse vo = new AjaxResponse(newe);
                    httpServletResponse.getWriter().print(vo.generateJSONString());
                    httpServletResponse.getWriter().flush();
                    httpServletResponse.getWriter().close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }

        }
        return null;
    }
}
